package com.wh.wisdomsite.xbox.server.controller.us;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.CommonFile;
import com.wh.wisdomsite.xbox.ba.entity.Role;
import com.wh.wisdomsite.xbox.ba.service.ICommonFileService;
import com.wh.wisdomsite.xbox.ba.service.IRoleService;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.us.UserIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.us.entity.UserRole;
import com.wh.wisdomsite.xbox.us.service.IUserRoleService;
import com.wh.wisdomsite.xbox.us.service.IUserService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.encrypt.md5.MD5Tool_Two;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 用户Controller
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.controller.us
 * @author: 丁奕
 * @date: 2018-08-03 15:49
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/user")
public class UserController {

    private static final Log logger = LogFactory.getLog(UserController.class);

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private ICommonFileService iCommonFileService;

    /**
     * 页面跳转
     * @return
     */
    @RequiresPermissions("rules:us_user_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index(){
        return "/us/user/userList";
    }

    /**
     * 获取用户集合
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:us_user_find")
    @RequestMapping(value = "/userList.do")
    public void userList(HttpServletResponse response, UserIn in){
        try {
            logger.info("加载用户数据列表-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<User> page = new Page<User>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<User> ewUser = new EntityWrapper<User>();
            ewUser.setEntity(new User());
            if(StringUtils.isNotEmpty(in.getLoginName())){
                ewUser.like("u.loginName", in.getLoginName());
            }
            if(StringUtils.isNotEmpty(in.getUserPhone())){
                ewUser.like("u.userPhone", in.getUserPhone());
            }
            if(StringUtils.isNotEmpty(in.getCompanyId())){
                ewUser.eq("u.companyId", in.getCompanyId());
            }
            if(StringUtils.isNotEmpty(in.getLoginStatus())){
                ewUser.eq("u.loginStatus", in.getLoginStatus());
            }
            if(StringUtils.isNotEmpty(in.getReceiveAlarm())){
                ewUser.eq("u.receiveAlarm", in.getReceiveAlarm());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewUser = UserUtils.setEntityWrapper(ewUser, "co", "off", "pr");
            }
            ewUser.orderBy("u.createDate", true);
            Page<Map<String, Object>> userPage = iUserService.getMapsPage(page, ewUser);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if(userPage.getRecords().size() > 0){
                for(Map<String, Object> user : userPage.getRecords()){
                    JSONObject object = new JSONObject(user);
                    object.put("id",user.get("usId"));
                    if(user.get("company") != null){
                        object.put("company",new JSONObject(user.get("company")));
                    }
                    if(user.get("employee") != null){
                        object.put("employee",new JSONObject(user.get("employee")));
                    }
                    array.put(object);
                }
            }
            json.put("total",userPage.getTotal());
            json.put("rows",array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载用户数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载用户数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取当前登录的用户信息
     * @param response
     */
    @RequestMapping(value = "/getCurrentUser.do")
    public void getCurrentUser(HttpServletResponse response){
        try {
            logger.info("获取当前登录用户信息-->>开始");
            JSONObject json = new JSONObject(UserUtils.getCurrentUser());
            ResManager.getTextOut(response).print(json);
            logger.info("获取当前登录用户信息-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("获取当前登录用户信息-->>Exception" + e.getMessage());
        }
    }

    /**
     * 用户详情
     * @param userIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:us_user_view")
    @RequestMapping("userDesc.do")
    public String userDesc(UserIn userIn, HttpServletRequest request) {
        logger.info("用户详情-->>开始");
        Map<String , Object> user = iUserService.getMapById(userIn.getId());
        if(user.get("createBy") != null){
            user.put("createBy", UserMapManager.getUserLoginNameInMap(user.get("createBy").toString()));
        }
        if(user.get("updateBy") != null){
            user.put("updateBy", UserMapManager.getUserLoginNameInMap(user.get("updateBy").toString()));
        }
        request.setAttribute("user", user);
        logger.info("用户详情-->>结束");
        return "/us/user/userDesc";
    }

    /**
     * 用户首页
     * @return
     */
    @RequiresPermissions("rules:us_user_homePage")
    @RequestMapping("homePage.do")
    public String homePage(HttpServletRequest request) {
        logger.info("用户首页-->>开始");
        String jsp = "";
        try{
            User user = UserUtils.getCurrentUser();
            if(!org.apache.commons.lang3.StringUtils.isEmpty(user.getEmId())){
                jsp = "officePage";
            }else{
                jsp = "companyPage";
            }
            logger.info("用户首页-->>结束");
        }catch (Exception e){
            e.printStackTrace();
        }
        return "/homePage/" + jsp;
    }

    /**
     * 跳转至添加或修改页面
     * @return
     */
    @RequestMapping("/toUserOption")
    public String toUserOption(String id, HttpServletRequest request){
        logger.info("添加修改用户跳转-->>开始");
        if(StringUtils.isNotEmpty(id)){
            //注入user参数
            User user = iUserService.selectById(id);
            Map<String, Object> userPhoto = iUserService.getMapById(id);
            request.setAttribute("user", user);
            request.setAttribute("userPhoto",userPhoto);
            //注入roleIds参数
            List<Role> roleList = iRoleService.getRoleListByUserId(id);
            String roleIds = "";
            if(roleList != null && !roleList.isEmpty()){
                for(Role role : roleList){
                    roleIds += role.getRoId() + ",";
                }
            }
            //删除menuIds的最后一个逗号
            if(roleIds.lastIndexOf(",") > 0){
                roleIds = roleIds.substring(0, roleIds.length() - 1);
            }
            request.setAttribute("roleIds", roleIds);
        }
        logger.info("添加修改用户跳转-->>结束");
        return "us/user/userOption";
    }

    /**
     * 更新或者修改
     * @param user
     * @param response
     */
    @RequiresPermissions("rules:us_user_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(User user, CommonFile commonFile, String fileName, String roleIds, HttpServletResponse response){
        try {
            User curUser = UserUtils.getCurrentUser();
            //判断用户是否已经存在,存在即更新.否则为添加
            if(StringUtils.isNotEmpty(user.getUsId())){
                logger.info("修改用户-->>开始");
                user.setUpdateDate(new Date());
                user.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                iUserService.deleteUserRoleByUserId(user.getUsId());
                //设置附件信息
                if(StringUtils.isNotEmpty(commonFile.getFileId())) {
                    if(!user.getUserPhoto().equals(commonFile.getFileId())){
                        commonFile.setName(fileName);
                        //添加附件信息
                        addCommonFile(user, commonFile, curUser);
                    }
                }
                user.setUserPhone(StringUtils.isEmpty(user.getUserPhone()) ?  null : user.getUserPhone());
                iUserService.updateById(user);
                //更新启动时加载的UserMap
                UserMapManager.updateUserToMap(user);
                //更新用户角色表
                saveUserRole(roleIds, user.getUsId());
                logger.info("修改用户-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("用户更新成功"));
            }else {
                logger.info("添加用户-->>开始");
                user.setCreateDate(new Date());
                user.setCreateBy(UserUtils.getCurrentUser().getUsId());
                user.setUsId(UUID.randomUUID().toString().replace("-",""));
                //给用户设置默认密码，默认密码为123456
                user.setPassword(MD5Tool_Two.MD5("123456"));
                if(StringUtils.isNotEmpty(commonFile.getFileId())){
                    commonFile.setName(fileName);
                    //添加附件信息
                    addCommonFile(user,commonFile,curUser);
                }
                user.setUserPhone(StringUtils.isEmpty(user.getUserPhone()) ?  null : user.getUserPhone());
                iUserService.insert(user);
                //更新启动时加载的UserMap
                UserMapManager.updateUserToMap(user);
                //更新用户角色表
                saveUserRole(roleIds, user.getUsId());
                logger.info("添加用户-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("用户添加成功"));

            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作用户-->>Exception" + e.getMessage());
        }
    }

    /**
     * 设置公共附件
     * @param user
     * @param commonFile
     * @param curUser
     */
    private void addCommonFile(User user, CommonFile commonFile, User curUser) {
        commonFile.setFkId(user.getUsId());
        commonFile.setCreateby(curUser.getUsId());
        commonFile.setCreatedate(new Date());
        commonFile.setCompCode(UserUtils.getServerSessionUser().getFinalCompCode());
        iCommonFileService.insert(commonFile);
        user.setUserPhoto(commonFile.getFileId());
    }

    /**
     * 保存所勾选的角色，维护用户角色表
     * @param roleIds
     * @param usId
     */
    private void saveUserRole(String roleIds, String usId) {
        //判断用户是否是超级管理员，若是超级管理员，则添加上超级管理员角色ID
        if(usId.equals("1")){
            roleIds += ",0";
        }
        //添加角色对应的菜单权限
        String[] roIds = roleIds.split(",");
        List<UserRole> userRoleList = new ArrayList<>();
        for (String roId : roIds) {
            UserRole userRole = new UserRole();
            userRole.setUrId(UUID.randomUUID().toString().replace("-",""));
            userRole.setRoId(roId);
            userRole.setUsId(usId);
            userRoleList.add(userRole);
        }
        if(!userRoleList.isEmpty()){
            iUserRoleService.insertBatch(userRoleList,roIds.length);
        }
    }

    /**
     * 删除用户
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:us_user_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除用户-->>开始");
            //验证是否是主账号
            if(id.equals("1")){
                ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("超级管理员用户不能被删除！"));
                return;
            }
            iUserService.deleteById(id);
            logger.info("删除用户-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("用户删除成功"));
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除用户-->>Exception" + e.getMessage());
        }
    }

    /**
     * 验证登陆名称是否已经存在
     * @param loginName
     * @param oldName
     * @return
     */
    @RequestMapping(value = "/loginNameIsExists.do", method = RequestMethod.POST)
    public void loginNameIsExists(HttpServletResponse response, String loginName, String oldName){
        Map<String, Object> map = new HashMap<>();
        map.put("result", iUserService.loginNameIsExists(loginName, oldName));
        JSONObject json = new JSONObject(map);
        ResManager.getTextOut(response).print(json);
    }

    /**
     * 验证用户手机是否已经存在
     * @param userPhone
     * @param oldPhone
     * @return
     */
    @RequestMapping(value = "/userPhoneIsExists.do", method = RequestMethod.POST)
    public void userPhoneIsExists(HttpServletResponse response, String userPhone, String oldPhone){
        Map<String, Object> map = new HashMap<>();
        map.put("result", iUserService.userPhoneIsExists(userPhone, oldPhone));
        JSONObject json = new JSONObject(map);
        ResManager.getTextOut(response).print(json);
    }

    /**
     * 用户个人信息页面跳转
     * @return
     */
    @RequestMapping("/toUserInformation.do")
    public String toUserInformation( HttpServletRequest request){
        logger.info("用户个人信息跳转-->>开始");
        //根据当前登陆的用户获取用户id
        String usId = UserUtils.getCurrentUser().getUsId();
        if(StringUtils.isNotEmpty(usId)){
            //注入user参数
            Map<String,Object> userInformation = iUserService.getMapById(usId);
            String userPhoto = (String)userInformation.get("userPhoto");
            CommonFile commonFile = iCommonFileService.selectById(userPhoto);
            userInformation.put("commonFile",commonFile);
            request.setAttribute("userInformation", userInformation);
            //注入roleIds参数
            List<Role> roleList = iRoleService.getRoleListByUserId(usId);
            String roleIds = "";
            if(roleList != null && !roleList.isEmpty()){
                for(Role role : roleList){
                    roleIds += role.getRoId() + ",";
                    request.setAttribute("role",role);
                }
            }
            //删除menuIds的最后一个逗号
            if(roleIds.lastIndexOf(",") > 0){
                roleIds = roleIds.substring(0, roleIds.length() - 1);
            }
            request.setAttribute("roleList", roleList);
        }
        logger.info("用户个人信息跳转-->>开始");
        return "us/user/userInformation";
    }

    /**
     * 用户个人信息保存
     */
    @RequestMapping(value = "/insertUserInformation.do",method = RequestMethod.POST)
    public void insertUserInformation(User user, CommonFile commonFile,String fileName, HttpServletResponse response){
        logger.info("修改用户个人信息-->>开始");
        try{
            if(StringUtils.isNotEmpty(user.getUsId())){
                user.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                user.setUpdateDate(new Date());
                //上传文件不为空
                if(StringUtils.isNotEmpty(commonFile.getFileId())){
                    user.setUserPhoto(commonFile.getFileId());
                }
                iUserService.updateById(user);
                //文件上传
                if(StringUtils.isNotEmpty(commonFile.getFileId())) {
                    commonFile.setFkId(user.getUsId());
                    commonFile.setName(fileName);
                    commonFile.setCompCode(UserUtils.getServerSessionUser().getFinalCompCode());
                    commonFile.setCreateby(UserUtils.getCurrentUser().getUsId());
                    commonFile.setCreatedate(new Date());
                    iCommonFileService.insert(commonFile);
                }
                response.getWriter().write(JsonUtil_Org.returnTrue("用户更新成功"));
            }
            logger.info("修改用户个人信息-->>结束");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
